package com.zjw.socket.demo.starter.core.ioc;


import com.zjw.socket.demo.starter.annotation.NonNull;
import com.zjw.socket.demo.starter.core.Reflector;

import java.util.HashSet;
import java.util.Set;

public final class IOCBeanInfo {

  public static final int STATE_INIT = -1;

  public static final int STATE_REFRESHING = 1;

  public static final int STATE_INJECTING = 2;

  public static final int STATE_COMPLETE = 3;

  @NonNull
  final String objectKey;

  final Class<?> type;
  @NonNull
  Object object;

  final Set<InjectRecord> incomeRefer = new HashSet<>();

  int state = STATE_INIT;

  public IOCBeanInfo(String objectKey, Object object) {
    this(objectKey, object, object.getClass());
  }

  public IOCBeanInfo(String objectKey, Object object, Class<?> type) {
    this.objectKey = objectKey;
    this.object = object;
    this.type = type;
  }

  public Class<?> getType() {
    return type;
  }

  public String getObjectKey() {
    return objectKey;
  }

  public Object get() {
    return object;
  }

  /**
   * 这是一个提供的可扩展方法，
   * 唯一可以改变Bean的Object熟悉值
   * 注意，为了安全起见，改变的值必须是原type实例，
   * 若不是，将抛出异常，
   */
  public void set(Object object) {
    if (!type.isInstance(object)) {
      throw new IllegalArgumentException("Illegal Object for type " + type + " :" + object);
    }
    this.object = object;

    reInject();
  }

  private void reInject() {
    for (InjectRecord injectRecord : incomeRefer) {
      Reflector.safeSetFiled(injectRecord.injectObject.object, injectRecord.injectField, this.object);
    }
  }
}
